<?php

declare(strict_types=1);

namespace App\Api\Service;

use App\Constants\OrderPayStatus;
use App\Constants\OrderStatus;
use App\Constants\SettingConfig;
use App\Model\Car;
use App\Model\Order;
use App\Utils\AliyunDyvmsapi;
use App\Utils\WechatPay;
use Carbon\Carbon;
use EasyWeChat\Pay\Message;
use Hyperf\DbConnection\Db;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class NotifyService
{
    /**
     * 微信支付
     * @return ResponseInterface
     */
    public function wechatPay(): ResponseInterface
    {
        $wechatPay = new WechatPay();
        return $wechatPay->notify(function (Message $message) use ($wechatPay) {
            // 商户订单号
            $outTradeNo = (string)$message->out_trade_no;

            // 商户号订单查询
            $response = $wechatPay->queryOrder($outTradeNo);
            if ($response['trade_state'] !== 'SUCCESS') {
                return;
            }

            // 查询订单
            $order = Order::query()
                ->where('pay_no', $outTradeNo)
                ->where('pay_status', OrderPayStatus::ING)
                ->first();
            if (is_null($order)) {
                return;
            }

            Db::beginTransaction();
            try {
                // 更新订单
                $order->pay_confirm_at = Carbon::now();
                $order->pay_status = OrderPayStatus::SUCCESS;
                $order->status = OrderStatus::ING;
                $order->save();

                // 更新车辆
                Car::query()
                    ->where('id', $order->car_id)
                    ->update([
                        'volume' => Db::raw('`volume` + 1'),
                    ]);

                Db::commit();
            } catch (Throwable $e) {
                Db::rollBack();
                business_error_logger(__FUNCTION__, $e);
            }

            // 发送阿里云语音通知
            $phone = ConfigService::get(SettingConfig::ORDER_NOTIFY_PHONE);
            if (!empty($phone)) {
                (new AliyunDyvmsapi())->singleCallByTts($phone, 'TTS_299555415');
            }
        });
    }
}
